﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SydEnergiDataService
{
    public class DataRepositoryService : IDataRepositoryService
    {
        public IEnumerable<CabinetDto> GetCabinets()
        {
            List<CabinetDto> cabinets;
            using(var context = new SydEnergiDataServiceDbContainer())
            {
                cabinets = context.CabinetDtos.Include("AddressDto").Include("Entries.AddressDto")
                    .Include("Entries.EntryHistory").ToList();
            }
            return cabinets;
        }

        public void SetCabinets(IEnumerable<CabinetDto> cabinets)
        {
            using (var context = new SydEnergiDataServiceDbContainer())
            {
                var cabinetDtos = context.CabinetDtos.Include("AddressDto").Include("Entries.AddressDto")
                    .Include("Entries.EntryHistory");

                foreach (var cabinetDto in cabinets)
                {
                    if (cabinetDtos.All(cabinet => cabinet.CabinetId != cabinetDto.CabinetId))
                    {
                        context.AddCabinet(cabinetDto);
                    }
                    else
                    {
                        var c = cabinetDtos.Single(cab => cab.CabinetId == cabinetDto.CabinetId);
                        context.DeleteCabinet(c);
                        context.SaveChanges();
                        context.AddCabinet(cabinetDto);
                        context.SaveChanges();
                    }
                }

                context.SaveChanges();
            }
        }
    }
}
